import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../../core/services/constant.service';
import { ServerService } from '../../../../../core/services/server.service';
import { StorageService } from '../../../../../core/services/storage.service';

@Component({
    selector: 'app-class-management',
    templateUrl: './class-management.component.html',
    styleUrls: ['./class-management.component.css']
})
export class ClassManagementComponent implements OnInit {
    classForm: FormGroup;               // 班级表单
    isVisible: boolean = false;         // 是否显示modal
    isConfirmLoading: boolean = false;  // modal中点击保存的时候的过渡效果
    isViewStateUpdate: boolean = false; // 页面是否是更新状态
    classList: object[] = [];           // 全部班级列表
    schoolId: string;                   // 学校id
    gradeList: object[] = [];           // 年级列表
    subjectList: object[] = [];         // 科目列表
    selectedGrade: string = '';         // 搜索条件,选中的年级
    _current: number = 1;               // 当前页
    _pageSize: number = 10;             // 每页数量
    _total: number = 1;                 // 数据总数
    _loading: boolean = true;           // 加载动画

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private message: NzMessageService
    ) {
        /**
         * 初始化班级表单
         * name: 班级名称
         * gradeId: 年级id
         * subjectIds: 科目id
         * count: 学生数量
         */
        this.classForm = this.fb.group({
            _id: [null],
            name: [null, [Validators.required, Validators.maxLength(10)]],
            gradeId: [null, Validators.required],
            subjectIds: [null, Validators.required],
            count: [null, Validators.required]
        });
        this.schoolId = this.storage.getItem(this.constant.storage.currentUser)['schoolId']['_id'];
    }

    ngOnInit() {
        this.getAllClasses(null);
        this.getAllGrades();
    }

    /**
     * 显示modal,添加或更新班级信息
     * @param id 
     */
    async showModal(id) {
        this.isVisible = true;
        // 首先获取年级列表和学科列表
        await Promise.all([this.getAllGrades(), this.getAllSubjects()]);
        if (id) {
            this.isViewStateUpdate = true;
            const result = await this.server.fetch(this.constant.api.manage.classM.findOne, { id });
            if (result) {
                this.classForm.setValue({
                    _id: result.data._id,
                    name: result.data.name,
                    gradeId: result.data.gradeId,
                    subjectIds: result.data.subjectIds,
                    count: result.data.studentsCount
                });
            }
        } else {
            if (this.gradeList.length > 0) {
                this.classForm.controls['gradeId'].setValue(this.gradeList[0]['_id']);
            }
            this.isViewStateUpdate = false;
        }
    }

    /**
     * 获取年级列表
     * @param schoolId 
     */
    async getAllGrades() {
        const param = {
            schoolId: this.schoolId
        };
        const allGrades = await this.server.fetch(this.constant.api.manage.grade.findAll, param);
        if (allGrades) {
            this.gradeList = allGrades.data.data;
        }
    }

    /**
     * 获取科目列表
     * @param schoolId 
     */
    async getAllSubjects() {
        const param = {
            schoolId: this.schoolId,
            page: 1,
            limit: 10000
        };
        const allSubjects = await this.server.fetch(this.constant.api.manage.subject.findAll, param);
        if (allSubjects) {
            this.subjectList = allSubjects.data.data;
        }
    }

    /**
     * 关闭modal
     * @param e 
     */
    handleCancel(e): void {
        this.classForm.reset({
            _id: null,
            name: null,
            subjectIds: [],
            count: 0
        });
        this.isVisible = false;
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.classForm.controls[name];
    }

    /**
     * 保存 || 更新
     * @param e 
     * @param school 
     */
    async handleOk(e, newClass): Promise<void> {
        newClass.schoolId = this.schoolId;
        this.isConfirmLoading = true;
        // 保存
        const result = await this.server.fetch(this.constant.api.manage.classM[this.isViewStateUpdate ? 'update' : 'save'], newClass);
        if (result) {
            this.message.success('保存班级成功');
            if (!this.isViewStateUpdate) {
                // 清空表单
                this.classForm.controls['name'].reset();
                this.classForm.controls['subjectIds'].reset();
                this.classForm.controls['count'].reset();
            } else {
                this.isVisible = false;
            }
            this.isConfirmLoading = false;
            this.getAllClasses(null);
        } else {
            this.isConfirmLoading = false;
        }

    }

    /**
     * 获取全部班级列表
     */
    async getAllClasses(gradeId): Promise<void> {
        const param = {
            schoolId: this.schoolId,
            limit: this._pageSize
        };
        // 如果存在年级id,添加查询参数
        if (gradeId) {
            param['gradeId'] = gradeId;
        }
        if (this._current !== 1) {
            param['date'] = this.classList[this.classList.length - 1]['createDate'];
        }
        const allClasses = await this.server.fetch(this.constant.api.manage.classM.findAll, param);
        if (allClasses) {
            this.classList = allClasses.data.data;
            this._total = allClasses.data.count;
            this._loading = false;
            // 转换科目数据
            if (this.classList.length > 0) {
                for (let c of this.classList) {
                    if (c['subjectIds'].length > 0) {
                        let str = [];
                        for (let subject of c['subjectIds']) {
                            str.push(subject.name);
                        }
                        c['subjectIds'] = str.join(' | ');
                    } else {
                        c['subjectIds'] = '暂无';
                    }
                }
            } else {
                this._loading = false;
            }
        } else {
            this._loading = false;
        }
    }

}
